package com.healthcloud.controller.modules.instrument;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;
import com.healthcloud.constants.InstrumentConsts;
import com.healthcloud.entity.*;
import com.healthcloud.entity.rent.InstrumentWechatEntity;
import com.healthcloud.service.*;
import com.healthcloud.service.rent.InstrumentWechatService;
import com.healthcloud.utils.*;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.healthcloud.annotation.SysLog;

import javax.servlet.http.HttpServletResponse;

/**
 * @author zj
 * 2017年6月23日 上午10:58:03
 */
@Controller
@RequestMapping(value = "/instrument")
public class BusInstrumentController {

    @Autowired
    private BusInstrumentService instrService;

    @Autowired
    private HlHospitalService hospService;

    @Autowired
    private CommonMethod commonMethod;

    @Autowired
    private InstrumentWechatService instrumentWechatService;

    @Autowired
    private BusRentService busRentService;

    @Autowired
    private HlHospitalService hlHospitalService;

    @ApiOperation(value = "设备列表页")
    @RequiresPermissions("instrument:list")
    @RequestMapping(value = "/toInstrumentMgr", method = RequestMethod.GET)
    public String toUserMgr() {
        return "bus/instrumentmgr";
    }

    @ApiOperation(value = "设备列表查询")
    @RequiresPermissions("instrument:list")
    @RequestMapping(value = "/searchInstrument", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> searchInstrument(BusInstrumentEntity bean, @ModelAttribute("pageParam") PageParam pageParam) {

        String ids = hlHospitalService.getChildeIds();
        bean.setHospIds(ids);

        List<BusInstrumentEntityVo> instrumentBeanVos = new ArrayList<BusInstrumentEntityVo>();
        List<BusInstrumentEntity> list = instrService.search(bean, pageParam);

        for (BusInstrumentEntity instrumentBean : list) {
            HlHospitalEntity hospitalBean = hospService.queryObject(instrumentBean.getHospId());
            BusInstrumentEntityVo instrumentBeanVo = new BusInstrumentEntityVo();
            BeanUtils.copyProperties(instrumentBean, instrumentBeanVo);
            if (hospitalBean != null) {
                instrumentBeanVo.setHospShortName(hospitalBean.getHospShortName());
            }
            instrumentBeanVos.add(instrumentBeanVo);
        }

        int count = instrService.count(bean);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("dataList", instrumentBeanVos);
        map.put("iTotalRecords", count);
        map.put("iTotalDisplayRecords", count);
        map.put("sEcho", pageParam.getsEcho());
        return map;
    }

    @ApiOperation(value = "设备新增或修改页")
    @RequiresPermissions("instrument:add")
    @RequestMapping(value = "/toUpdateInstr", method = RequestMethod.GET)
    public String toUpdateInstr(Long id, String method, Model model) {
        BusInstrumentEntity entity = null;
        if ("2".equals(method)) {
            entity = instrService.searchById(id);
        }
        model.addAttribute("entity", entity);
        model.addAttribute("method", method);
        model.addAttribute("hospital", commonMethod.getHospitalBean());

        if (entity != null && entity.getHospId() != null) {
            HlHospitalEntity hospital = hospService.queryObject(entity.getHospId());
            model.addAttribute("hospital", hospital);
        }

        return "bus/updateinstrument";
    }

    @ApiOperation(value = "添加或修改设备")
    @RequiresPermissions("instrument:add")
    @RequestMapping(value = "/updateInstr", method = RequestMethod.POST)
    public @ResponseBody
    ApiRes updateInstr(BusInstrumentEntity bean) {
        if (bean.getInstrumentId() == null) {
            instrService.createInstr(bean);
        } else {
            instrService.updateInstr(bean);
        }
        return new ApiRes(true, null, null, null);
    }

    @ApiOperation(value = "删除设备")
    @RequiresPermissions("instrument:delete")
    @SysLog("删除设备")
    @RequestMapping(value = "/deleteInstr", method = RequestMethod.POST)
    public @ResponseBody
    ApiRes deleteInstr(Long[] ids) {
        int[] idArr = new int[ids.length];
        // TODO 参数检测
        for (int i = 0; i < ids.length; i++) {
            Integer l = null;
            try {
                l = ids[i].intValue();
                idArr[i] = l;
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

        }

        //已经出租，已经投放的设备的不可以刪除，
        BusInstrumentEntity instrumentBean = instrService.searchById(ids[0]);
        if (InstrumentConsts.NSTRUMENT_STATUS_RENT.equals(instrumentBean.getInstrumentStatus()) ||
                InstrumentConsts.INSTRUMENT_STATUS_INSTALL.equals(instrumentBean.getInstrumentStatus())) {
            return new ApiRes(false, null, null, "已经出租的不可以刪除");
        }

        instrService.deletes(idArr);
        return new ApiRes(true, null, null, null);
    }

    @ApiOperation(value = "选择设备", notes = "只能查询到自己医院")
    @RequiresPermissions("instrument:list")
    @RequestMapping(value = "/selectInstr", method = RequestMethod.POST)
    @ResponseBody
    public ApiRes selectInstr(String limit, String offset, String name) {
        List<BusInstrumentEntity> list = instrService.searchByName(name, offset, limit, commonMethod.getHospitalId());
        int total = instrService.countByName(name, commonMethod.getHospitalId());
        return new ApiRes(true, list, null, String.valueOf(total));
    }

    @ApiOperation(value = "设备详情页")
    @RequiresPermissions("instrument:list")
    @RequestMapping(value = "/toInfo", method = RequestMethod.GET)
    public String toInfo() {
        return "bus/instrument/info";
    }

    /**
     * 设备详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "设备详情")
    @RequestMapping(value = {"/info", "/n/info"}, method = RequestMethod.POST)
    @ResponseBody
    public ApiRes info(Long id) throws Exception {
        //设备信息
        BusInstrumentEntity instrument = instrService.searchById(id);
        JSONObject jo = JSONObject.fromObject(instrument);
        //医院名
        if (instrument.getHospId() != null) {
            HlHospitalEntity hospital = hospService.queryObject(instrument.getHospId());
            if (hospital != null) {
                jo.put("hospitalName", hospital.getHospShortName());
            }
        }
        //绑定记录
        List<InstrumentWechatEntity> iws = new ArrayList<>();
        if (StringUtils.isNotEmpty(instrument.getInstrumentSN())) {
            InstrumentWechatEntity iw = new InstrumentWechatEntity();
            iw.setSn(instrument.getInstrumentSN());
            iws = instrumentWechatService.queryList(iw, null);
        }
        //目前租赁情况
        BusRentEntity r = null;
        if ("2".equals(instrument.getInstrumentStatus())) {
            BusRentEntity rent = new BusRentEntity();
            rent.setInstrumentSN(instrument.getInstrumentSN());
            rent.setRentStatus("0");
            PageParam page = new PageParam();
            page.setiDisplayStart(0);
            page.setiDisplayLength(1);
            List<BusRentEntity> rents = busRentService.queryList(rent, page);
            if (rents != null && rents.size() > 0) {
                r = rents.get(0);
            }
        }

        Map map = new HashMap();
        map.put("ies", iws);
        map.put("instrument", jo);
        map.put("rent", r);
        return new ApiRes(map);
    }

    /**
     * 设备二维码获取
     *
     * @param sn
     * @return
     */
    @ApiOperation(value = "设备二维码获取")
    @RequestMapping(value = {"/qrcode", "/n/qrcode"}, method = RequestMethod.POST)
    @ResponseBody
    public ApiRes qrcode(String sn) {
        String url = "http://weshop.nbmedicalsystem.com/wechat/qrCode/wx7eeac5736e7fb5ba" + "/" + sn;
        String qrcodeUrl = com.alibaba.fastjson.JSONObject.parseObject(HttpClientUtil.doGet(url)).getString("data");
        return new ApiRes(qrcodeUrl);
    }

    @ApiOperation(value = "查看设备权限(仅微信)")
    @RequestMapping(value = "/n/check", method = RequestMethod.GET)
    public void toCheckInstrument(HttpServletResponse response, Long instrumentId) throws IOException {
        response.sendRedirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
                PropertiesUtils.getProperty("app_id") +
                "&redirect_uri=" +
                PropertiesUtils.getProperty("http_wechat") +
                "/report-view/wechat/checkInstrument?instrumentId=" +
                instrumentId +
                "&response_type=code&scope=snsapi_base&state=123#wechat_redirect");
    }

    @ApiOperation(value = "删除微信设备绑定")
    @RequestMapping(value = {"/deletedInstrumentWechat", "/n/deletedInstrumentWechat"}, method = RequestMethod.POST)
    @ResponseBody
    public ApiRes deletedInstrumentWechat(Long id) {
        instrumentWechatService.delete(id);
        return ApiRes.SUCCESS;
    }

    @ApiOperation(value = "修改微信设备绑定")
    @RequestMapping(value = {"/updateInstrumentWechat", "/n/updateInstrumentWechat"}, method = RequestMethod.POST)
    @ResponseBody
    public ApiRes updateInstrumentWechat(InstrumentWechatEntity entity) {
        instrumentWechatService.update(entity);
        return ApiRes.SUCCESS;
    }


    @ApiOperation(value = "可绑定设备列表")
    @RequestMapping(value = "/getList", method = RequestMethod.POST)
    public @ResponseBody
    ApiRes getList() {
        ArrayList<String> strings = Lists.newArrayList("亲智血糖仪", "B21G血压计");
        return new ApiRes(true, strings, null, null);
    }
}
